package com.example.springcloud.controller;

import com.example.springcloud.lb.LoadBalance;
import com.example.springcloud.utils.Constant;
import com.example.springcloud.utils.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * The type Order controller.
 */
@RestController
@RequestMapping(value = "/consumer")
@Slf4j
public class OrderController {

    @Resource
    private LoadBalance loadBalance;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource // 注入 RestTemplate
    private RestTemplate restTemplate; // 需要用这个工具在 80 端口访问 8001 端口

    private int count = 1;

    @GetMapping(value = "/testMyBalances/payment/get/{id}")
    public ResultEntity testMyBalances(@PathVariable(value = "id") Long id) {

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if (instances == null || instances.size() <= 0) {
            return new ResultEntity(Constant.RESPONSE_CODE_500);
        }
        ServiceInstance instance = loadBalance.getInstance(instances);

        URI uri = instance.getUri();

        System.out.println((count++) + " - uri = " + uri);

        return restTemplate.getForObject(uri + "/spring-cloud//payment/get/" + id, ResultEntity.class);

    }

}
